<template>
	<view>
		<view v-show="!showLocation" class="alldiv">
			<view class="topBox">
				<!-- 第一层返回 -->
				<view class="topdiv">
					<image src='@/static/icon/shop/topBj2.png' class="background-image"></image>
					<view class="navdiv" @click="navigateBack">
						<u-icon :customStyle="{ marginRight: 32 + 'rpx' }" name="arrow-left" size="17"
							color="rgba(0,0,0,0.9)" labelColor="rgba(0,0,0,0.9)"
							:label="language.FreeRide.sfc"></u-icon>
					</view>
				</view>
			</view>
			<view class="bodydiv">
				<!-- 耐心等待 -->
				<text class="title van-ellipsis">
					{{ language.FreeRide.ddczyq }}
					<image src='@/static/icon/loading.png' class="loading"></image>
					<!-- <text @click="order">模拟接单</text> -->
				</text>
				<view class="item" style="margin-top: 10px;">
					<text class="sub-title van-ellipsis">{{ language.FreeRide.qnxdd }}</text>
					<!-- <view class="wait-time">
            <view><text class="green">{{ waitTime }}</text>{{ language.FreeRide.minute }}</view>
            <text class="sub-title van-ellipsis">{{ language.FreeRide.czpjyysj }}</text>
          </view> -->
					<!-- 地址 -->
					<view class="address-box" v-show="startAddress">
						<view class="date" v-show="goTime">
							<u-icon style="margin-right: 16rpx;" name="clock-fill" size="12"></u-icon>
							{{ goTime }}
						</view>
						<view class="origin-station">
							<text class="van-ellipsis">{{ startAddress }}</text>
						</view>
						<view class="destination">
							<text class="van-ellipsis">{{ endAddress }}</text>
						</view>
					</view>
					<!-- 操作 -->
					<view class="other-use">
						<view class="other-use-item" v-for="item in otherUseList" :key="item.id"
							@click="optionFun(item.id)">
							<u-icon :name="item.icon" size="16"></u-icon>
							<view class="name">{{ item.name }}</view>
						</view>
					</view>
					<!-- <text @click="order">模拟节点</text> -->
				</view>
				<!-- 通知顺路顺风车 -->
				<!-- <text class="title van-ellipsis" style="margin: 16px 0 -6px 0;display: block;font-size: 24rpx;">
          {{ language.FreeRide.zzwntzsldsfc }}
        </text>
        <view class="item" v-for="driver in driverList">
          <view class="driver-info">
            <view class="profile-photo mr10">
              <u-avatar :src="driver.photo"></u-avatar>
            </view>
            <view class="driver-name mr10">{{ driver.name }}</view>
            <view class="license-plate mr10">{{ driver.day }} {{ driver.time }}</view>
            <view class="green">{{ driver.num }}{{ language.FreeRide.sl }}</view>
          </view>
          <view class="address-box">
            <view class="origin-station">
              {{ startAddress }}<view class="sub-title" style="margin-left: 4px;">10.4km</view>
            </view>
            <view class="destination">
              {{ endAddress }}<view class="sub-title" style="margin-left: 4px;">10.4km</view>
            </view>
            <text class="description">已有拼友 · 暂未在本线路出行过</text>
          </view>
          <view class="driver">
            <text class="sub-title van-ellipsis">{{ language.FreeRide.zzxzslczck }}</text>
            <text class="driver-btn">{{ language.FreeRide.lxcz }}</text>
          </view>
        </view> -->
			</view>
		</view>
		<SelectLocation ref="selectLocation" v-if="showLocation" :language="language" :locationType="1"
			@navigateBack="locationBack" @selectLocation="selectLocation"></SelectLocation>
		<view id="map" style="display: none;"></view>
	</view>
</template>

<script>
	import {
		getTaxiOrder,
		cancelOrder,
		getInquiryprice
	} from '@/api/driver'
	import SelectLocation from '@/components/hailCar/SelectLocation.vue';
	export default {
		components: {
			SelectLocation
		},
		data() {
			return {
				language: {},
				waitTime: '10-15',
				goTime: '',
				startAddress: '',
				endAddress: '',
				otherUseList: [],
				// driverList: [{
				//   photo: require('@/static/image/BankCard.png'),
				//   name: '李师傅',
				//   day: '明天',
				//   time: '18:00',
				//   num: '90%'
				// }],
				orderInfo: {}, // 订单信息
				orderId: 0, // 订单id
				showLocation: false,
				intervalId: 0
			}
		},
		// onReady: function() {
		//   console.log(wssocket)
		//   wssocket.onMessage(this.onMessage)
		//   const token = uni.getStorageSync('token')
		// 	console.log(token)
		//   wssocket.connect(`ws://decimalism.natapp1.cc/ws?token=${token}`, token)
		//   wssocket.init()
		// },
		beforeDestroy() {
			// wssocket.close();
			this.intervalId && clearInterval(this.intervalId)
		},
		onLoad(option) {
			if (!option.id) {
				this.navigateBack()
			}
			console.log(option.id)
			this.orderId = option.id
			this.getlanguagedata();
			this.getOrder()
			this.intervalId = setInterval(this.getOrder, 3000)
			// 模拟接单
			// this.order()
		},
		methods: {
			order() {
				try {
					cancelOrder({
						driverId: 335,
						orderId: this.orderId
					}).then(res => {}).catch(error => {});
				} catch (error) {
					console.log(error)
				}
			},
			navigateBack() {
				uni.reLaunch({
					url: '/pages/Home/Home'
				});
			},
			goNext() {
				if (this.orderId && this.driverId) {
					uni.redirectTo({
						url: `/pages/Home/freeRide/waitPay?id=${this.orderId}`,
					});
				}
			},
			getlanguagedata() {
				this.language =
					this.$store.getters["internationalization/getinternationalization"];
				this.otherUseList = [{
						id: 0,
						icon: require('@/static/image/message.png'),
						name: this.language?.FreeRide.wdxx, // 我的消息
					},
					{
						id: 1,
						icon: require('@/static/image/dial.png'),
						name: this.language?.FreeRide.lxsj, // 联系司机
					},
					// {
					// 	id: 2,
					// 	icon: require('@/static/image/pen.png'),
					// 	name: this.language.FreeRide.xgmdd, // 修改目的地
					// },
					{
						id: 3,
						icon: require('@/static/image/cancel.png'),
						name: this.language.FreeRide.qxxc, // 取消行程
					},
				]
			},
			async getOrder() {
				try {
					await getTaxiOrder({
						id: this.orderId
					}).then(res => {
						if (res.code === 0) {
							if (Number(res.data.orderStatus)) {
								// 已接单
								this.intervalId && clearInterval(this.intervalId)
								uni.navigateTo({
									url: `/pages/Home/freeRide/waitPay?id=${this.orderId}`,
								});
							}
							this.orderInfo = res.data
							if (res.data?.planStartTime && res.data?.planEndTime) {
								this.goTime = this.convertDateString(res.data?.planStartTime) + ' - ' + this
									.convertDateString(res.data?.planEndTime)
							}
							this.startAddress = res.data.startPlace;
							this.endAddress = res.data.endPlace;
						}
					})
				} catch (error) {
					console.log(error)
				}
			},
			convertDateString(dateString) {
				// 使用正则表达式提取日期和时间部分
				const [datePart, timePart] = dateString?.split(' ');
				const [year, month, day] = datePart?.split('-');
				const [hours, minutes] = timePart?.split(':');

				// 格式化为目标格式
				return `${year}${this.language?.FreeRide.year}${month}${this.language?.FreeRide.month}${day}${this.language?.FreeRide.day} ${hours}:${minutes}`;
			},
			// 操作
			optionFun(id) {
				if (!this.orderId) return
				switch (id) {
					case 2:
						// 修改目的地
						this.showLocation = true;
						break;
					case 3:
						// 取消行程
						uni.showLoading({
							title: 'loading...'
						});
						try {
							cancelOrder({
								orderId: this.orderId,
								orderStatus: 3
							}).then(res => {
								uni.showToast({
									title: this.language.Takingataxi.orderCancelSuccess,
									icon: "none"
								});
								uni.hideLoading();
								uni.navigateTo({
									url: `/pages/Home/freeRide/tripCancellation?id=${this.orderId}`,
								});
							}).catch(error => {
								uni.hideLoading();
							});
						} catch (error) {
							uni.hideLoading();
							console.log(error)
						}
						break;
				}
			},
			// 取消选择目的地
			locationBack() {
				this.showLocation = false;
			},
			// 确定目的地
			async selectLocation(location) {
				uni.showLoading({
					title: 'loading...'
				});
				const {
					startLatitude,
					startLongitude
				} = this.orderInfo;
				const distance = await this.$refs.selectLocation.calculateDistance({
					latitude: startLatitude,
					longitude: startLongitude
				}, location)
				let exclusiveNum = 0;
				try {
					await getInquiryprice({
						distance: distance
					}).then(res => {
						if (res.code === 0) {
							exclusiveNum = res.data
						}
					}).catch(error => {
						uni.hideLoading();
					});
				} catch (error) {
					console.log(error)
					uni.hideLoading();
				}
				if (exclusiveNum) {
					try {
						await cancelOrder({
							orderId: this.orderId,
							endPlace: location.address,
							endLongitude: location.longitude,
							endLatitude: location.latitude,
							distance: distance,
							cost: exclusiveNum
						}).then(async res => {
							uni.showToast({
								title: this.language.PersonalInformation.prompt,
								icon: "none"
							});
							await this.getOrder()
							uni.hideLoading();
						}).catch(error => {
							uni.hideLoading();
						});
					} catch (error) {
						uni.hideLoading();
						console.log(error)
					}
					this.locationBack()
				}
			},
			// websocket 通讯
			onMessage(cmd, data) {
			}
		}
	}
</script>

<style scoped lang="less" src="@/static/css/takingataxi.less"></style>
<style lang="less" scoped>
	.alldiv {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.topBox {
			position: relative;
			width: 100%;
			background: linear-gradient(94.07deg, rgba(235, 255, 236, 1) 0%, rgba(220, 247, 242, 1) 100%);
			overflow: hidden;
			flex-shrink: 0;

			.background-image {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
			}

			// 这个是搜索和返回样式
			.topdiv {
				width: 100%;
				height: 180px;
				display: flex;
				margin: calc(var(--status-bar-height) + 10px) 0 4px 0;

				// 这个是返回样式
				.navdiv {
					position: relative;
					margin-left: 17px;
					height: 34px;
					display: flex;
					justify-content: center;
					overflow: hidden;

					::v-deep {
						.u-icon__label {
							font-size: 14px;
						}
					}
				}
			}
		}

		.bodydiv {
			position: relative;
			flex: 1;
			height: 0;
			overflow-y: auto;
			background-color: #fff;
			margin-top: -134px;
			border-radius: 20px 20px 0px 0px;
			box-shadow: 0px -3px 6px rgba(6, 145, 161, 0.05);
			padding: 24px 16px;

			.title {
				font-size: 32rpx;
				font-weight: 700;
				color: rgba(56, 56, 56, 1);
			}

			.item {
				border-radius: 16px;
				box-shadow: 0px 2px 4px rgba(5, 48, 7, 0.08);
				margin-top: 16px;
				padding: 12px 16px;
			}

			.sub-title {
				font-size: 20rpx;
				color: rgba(153, 153, 153, 1);
			}

			.wait-time {
				text-align: center;
				font-size: 20rpx;
				color: rgba(51, 51, 51, 1);

				.green {
					font-size: 24px;
					font-weight: 700;
					color: rgba(47, 212, 184, 1);
				}
			}

			.driver {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 16rpx;

				.driver-btn {
					font-size: 20rpx;
					color: rgba(153, 153, 153, 1);
					padding: 4px 6px;
					border: 1px solid rgba(204, 204, 204, 1);
					border-radius: 15px;
				}
			}
		}

		.loading {
			width: 12px;
			height: 12px;
			margin-left: 6px;
			animation: round 2s infinite ease;

			@keyframes round {
				0% {
					transform: rotate(0deg);
				}

				100% {
					transform: rotate(360deg);
				}
			}
		}
	}
</style>